package com.example.androidmainshixun.view;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.androidmainshixun.R;
import com.example.androidmainshixun.adapter.MessageAdapter;
import com.example.androidmainshixun.entity.Messages;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;


public class ChatActivity extends AppCompatActivity {

    private RecyclerView messagesRecyclerView;
    private EditText messageEditText;
    private Button sendButton;
    private MessageAdapter messageAdapter;
    private List<Messages> messagess;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_activity);

        messagesRecyclerView = findViewById(R.id.messagesRecyclerView);
        messageEditText = findViewById(R.id.messageEditText);
        sendButton = findViewById(R.id.sendButton);
        messagess = new ArrayList<>();
        messageAdapter = new MessageAdapter(messagess);
        messagesRecyclerView.setAdapter(messageAdapter);
        messagesRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String messageContent = messageEditText.getText().toString();
                if (!messageContent.matches("^[\u4e00-\u9fa5]+$")) {
                    // 显示错误提示，内容包含非中文字符
                    Toast.makeText(ChatActivity.this, "仅支持发送中文字符", Toast.LENGTH_SHORT).show();
                    return; // 阻止发送
                }else {
                    String senderId = "当前用户ID"; // 需要替换为实际的用户ID
                    String receiverId = "接收者ID"; // 需要替换为实际的接收者ID
                    // 获取当前时间，并格式化为 "HH:mm"
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
                    String formattedTimestamp = sdf.format(new Date());
                    // 创建消息并添加到列表
                    Messages messages=new Messages(senderId, receiverId, messageContent, formattedTimestamp);
                    messagess.add(messages);
                    messageAdapter.notifyItemInserted(messagess.size() - 1);
                    messagesRecyclerView.scrollToPosition(messagess.size() - 1);
                    messageEditText.setText(""); // 清空输入框
                }
            }
        });
    }
}